<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" width="40%">
    <a-card :bordered="false" style="height: 100%">
      <a-tabs v-model:activeKey="activeKey" @change="tabChange">
        <a-tab-pane key="basicComponents01" tab="基本信息" />
        <a-tab-pane key="basicComponents02" tab="产品价格" />
        <a-tab-pane key="basicComponents03" tab="电商平台销售价格" />
        <a-tab-pane key="basicComponents04" tab="产品英文资料" />
        <a-tab-pane key="basicComponents05" tab="产品发货" />
        <a-tab-pane key="basicComponents06" tab="产品图片" />
        <a-tab-pane key="basicComponents07" tab="产品视频" />
        <a-tab-pane key="basicComponents08" tab="产品日志" />
      </a-tabs>
      <template v-for="(component, key) in componentType" :key="key + '_' + formResetKey">
        <component v-show="activeKey === key" :is="component" :ref="setComponentRef(key)" :is-update="isUpdate" :record="record" />
      </template>
    </a-card>
    <template #footer>
      <div style="text-align: center">
        <a-button key="back" @click="handleClose">关闭</a-button>
      </div>
    </template>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref, getCurrentInstance, watch, nextTick } from 'vue';
  import { useRoute } from 'vue-router';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import basicComponents01 from './components/basicComponents.vue';
  import basicComponents02 from './components/basicComponents02.vue';
  import basicComponents03 from './components/basicComponents03.vue';
  import basicComponents04 from './components/basicComponents04.vue';
  import basicComponents05 from './components/basicComponents05.vue';
  import basicComponents06 from './components/basicComponents06.vue';
  import basicComponents07 from './components/basicComponents07.vue';
  import basicComponents08 from './components/basicComponents08.vue';

  // 获取当前组件实例
  const instance = getCurrentInstance();
  const route = useRoute();
  const isUpdate = ref(true);
  const record = ref<any>({});
  const formResetKey = ref(0);
  const activeKey = ref('basicComponents01');

  // 创建组件引用映射
  const componentRefs = ref({});

  const [registerModal, { closeModal, setModalProps }] = useModalInner(async (data) => {
    setModalProps({
      defaultFullscreen: true,
      confirmLoading: false,
      showCancelBtn: data?.showFooter,
      showOkBtn: data?.showFooter,
    });
    isUpdate.value = !!data?.isUpdate;
    console.log('data', isUpdate.value);

    if (!data?.isUpdate) {
      console.log('新增');
      record.value = {};
      activeKey.value = 'basicComponents01';
      formResetKey.value += 1;
      nextTick(() => {
        updateAllTabData({});
      });
    } else if (data?.record) {
      activeKey.value = 'basicComponents01';
      console.log('GoodsDetail编辑record', data.record);
      record.value = data.record;
      nextTick(() => {
        refreshFormData();
      });
    }
  });

  const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  // 组件类型映射
  const componentType = {
    basicComponents01: basicComponents01,
    basicComponents02: basicComponents02,
    basicComponents03: basicComponents03,
    basicComponents04: basicComponents04,
    basicComponents05: basicComponents05,
    basicComponents06: basicComponents06,
    basicComponents07: basicComponents07,
    basicComponents08: basicComponents08,
  };

  // 设置组件引用的函数
  function setComponentRef(key) {
    return (el) => {
      if (el) {
        componentRefs.value[key] = el;
      }
    };
  }

  function refreshFormData() {
    // console.log('refreshFormData');
    const currentRef = componentRefs.value[activeKey.value];
    if (currentRef && typeof currentRef.setFormValues === 'function') {
      console.log('刷新表单数据', record.value);
      currentRef.setFormValues(record.value);
    }
  }

  // 使用component动态切换tab
  function tabChange(key) {
    activeKey.value = key;
    // 切换时刷新当前表单数据
    nextTick(() => {
      refreshFormData();
    });
  }

  // 监听 isUpdate 变化
  watch(isUpdate, (newVal) => {
    // 通知所有组件更新状态
    Object.keys(componentRefs.value).forEach((key) => {
      const componentRef = componentRefs.value[key];
      if (componentRef && typeof componentRef.setIsUpdate === 'function') {
        componentRef.setIsUpdate(newVal);
      }
    });
  });

  // 更新所有tab组件的数据
  function updateAllTabData(data) {
    console.log('updateAllTabData', data);
    Object.keys(componentRefs.value).forEach((key) => {
      const componentRef = componentRefs.value[key];
      if (componentRef) {
        if (!data?.isUpdate) {
          console.log('新增');
          // const emptyFields = {
          //   id: undefined,
          //   customizeCode: undefined,
          //   goodsCode: undefined,
          //   goodsNameCn: undefined,
          //   goodsName: undefined,
          //   categoryId: undefined,
          //   categoryId_children: undefined,
          //   goodsBrand: undefined,
          //   compatibleBrand: undefined,
          //   compatibleModel: undefined,
          //   infringementRisk: undefined,
          //   referenceLink: undefined,
          //   valueType: undefined,
          //   productFeatures: undefined,
          //   remark: undefined,
          //   goodsLogistics: undefined,
          //   productMaterial: undefined,
          //   productCertification: undefined,
          //   goodsUnit: undefined,
          //   packaging: undefined,
          //   quality: undefined,
          //   inventoryAttributes: undefined,
          //   labelModel: undefined,
          //   labelQuality: undefined,
          //   defaultWarehouse: undefined,
          //   defaultWarehouse_code: undefined,
          //   defaultLocation: undefined,
          //   defaultLocation_code: undefined,
          //   barcodeScheme: undefined,
          //   barcodeScheme_code: undefined,
          //   procurementPersonnel: undefined,
          //   developers: undefined,
          //   responsibleOfficer: undefined,
          //   createTime: undefined,

          //   // Price fields (formSchema02)
          //   supplySituation: undefined,
          //   supplier: undefined,
          //   supplier_code: undefined,
          //   mainlandCost: undefined,
          //   mainlandQuotation: undefined,
          //   MainlandProfitMargin: undefined,
          //   hkCost: undefined,
          //   hkQuotation: undefined,
          //   hkProfitMargin: undefined,

          //   // E-commerce price fields (formSchema03)
          //   ebayProfitMargin: undefined,
          //   ebayReferencePrice: undefined,
          //   ebayBulkPrice: undefined,
          //   aliExpressProfitMargin: undefined,
          //   aliExpressReferencePrice: undefined,
          //   aliExpressBulkPrice: undefined,

          //   // English info fields (formSchema04)
          //   englishName: undefined,
          //   englishShortName: undefined,
          //   websiteTitle: undefined,
          //   websiteDescription: undefined,

          //   // Packaging info fields (formSchema05)
          //   HYCweight: undefined,
          //   HYCsize: undefined,
          //   packagingType: undefined,
          //   packagingId: undefined,
          //   actualWeight: undefined,
          //   length: undefined,
          //   width: undefined,
          //   height: undefined,
          //   volumeWeight: undefined,

          //   // Image fields (formSchema06)
          //   coverPic: undefined,
          //   websitePic: undefined,
          //   ebayPic: undefined,
          //   aliExpressPic: undefined,
          //   alibabaPic: undefined,
          //   otherPics: undefined,

          //   // Video fields (formSchema07)
          //   websiteVideos: undefined,
          //   testVideos: undefined,
          //   casualVideos: undefined,
          //   otherVideos: undefined,

          //   goodsPrice: '',
          //   goodsInfo: '',
          //   goodsSale: '',
          //   goodsEnglish: '',
          //   goodsDeliver: '',
          //   goodsPic: '',
          //   goodsVideo: '',
          //   goodsExtend: '',
          // };

          // if (typeof componentRef.resetFields === 'function') {
          //   componentRef.resetFields();
          // } else if (typeof componentRef.setFormValues === 'function') {
          //   componentRef.setFormValues(emptyFields);
          // }
        } else {
          if (typeof componentRef.setFormValues === 'function') {
            console.log('setFormValues', data);
            componentRef.setFormValues(data);
          }
        }
      }
    });
  }

  async function saveSpecificTab(tabKey) {
    console.log(tabKey, 'tabKeytabKey');
    const componentRef = componentRefs.value[tabKey];
    if (componentRef && typeof componentRef.handleSubmit === 'function') {
      try {
        const result = await componentRef.handleSubmit();
        console.log('子组件保存返回', result);
        if (result.success && result.data) {
          switch (tabKey) {
            case 'basicComponents01':
              record.value.goodsInfo = result.data.goodsInfo;
              break;
            case 'basicComponents02':
              record.value.goodsPrice = result.data.goodsPrice;
              break;
            case 'basicComponents03':
              record.value.goodsSale = result.data.goodsSale;
              break;
            case 'basicComponents04':
              record.value.goodsEnglish = result.data.goodsEnglish;
              break;
            case 'basicComponents05':
              record.value.goodsDeliver = result.data.goodsDeliver;
              break;
            case 'basicComponents06':
              record.value.goodsPic = result.data.goodsPic;
              break;
            case 'basicComponents07':
              record.value.goodsVideo = result.data.goodsVideo;
              break;
            default:
              break;
          }
          return result;
        }
      } catch (error) {
        console.error(`Error saving tab ${tabKey}:`, error);
        throw error;
      }
    }
    return { success: false };
  }

  // 处理关闭按钮点击
  async function handleClose() {
    nextTick(() => {
      record.value = {
        id: undefined,
        customizeCode: undefined,
        goodsCode: undefined,
        goodsNameCn: undefined,
        goodsName: undefined,
        categoryId: undefined,
        categoryId_children: undefined,
        goodsBrand: undefined,
        compatibleBrand: undefined,
        compatibleModel: undefined,
        infringementRisk: undefined,
        referenceLink: undefined,
        valueType: undefined,
        productFeatures: undefined,
        remark: undefined,
        goodsLogistics: undefined,
        productMaterial: undefined,
        productCertification: undefined,
        goodsUnit: undefined,
        packaging: undefined,
        quality: undefined,
        inventoryAttributes: undefined,
        labelModel: undefined,
        labelQuality: undefined,
        defaultWarehouse: undefined,
        defaultWarehouse_code: undefined,
        defaultLocation: undefined,
        defaultLocation_code: undefined,
        barcodeScheme: undefined,
        barcodeScheme_code: undefined,
        procurementPersonnel: undefined,
        developers: undefined,
        responsibleOfficer: undefined,
        createTime: undefined,

        // Price fields (formSchema02)
        supplySituation: undefined,
        supplier: undefined,
        supplier_code: undefined,
        mainlandCost: undefined,
        mainlandQuotation: undefined,
        MainlandProfitMargin: undefined,
        hkCost: undefined,
        hkQuotation: undefined,
        hkProfitMargin: undefined,

        // E-commerce price fields (formSchema03)
        ebayProfitMargin: undefined,
        ebayReferencePrice: undefined,
        ebayBulkPrice: undefined,
        aliExpressProfitMargin: undefined,
        aliExpressReferencePrice: undefined,
        aliExpressBulkPrice: undefined,

        // English info fields (formSchema04)
        englishName: undefined,
        englishShortName: undefined,
        websiteTitle: undefined,
        websiteDescription: undefined,

        // Packaging info fields (formSchema05)
        HYCweight: undefined,
        HYCsize: undefined,
        packagingType: undefined,
        packagingId: undefined,
        actualWeight: undefined,
        length: undefined,
        width: undefined,
        height: undefined,
        volumeWeight: undefined,

        // Image fields (formSchema06)
        coverPic: undefined,
        websitePic: undefined,
        ebayPic: undefined,
        aliExpressPic: undefined,
        alibabaPic: undefined,
        otherPics: undefined,

        // Video fields (formSchema07)
        websiteVideos: undefined,
        testVideos: undefined,
        casualVideos: undefined,
        otherVideos: undefined,

        goodsPrice: '',
        goodsInfo: '',
        goodsSale: '',
        goodsEnglish: '',
        goodsDeliver: '',
        goodsPic: '',
        goodsVideo: '',
        goodsExtend: '',
      };
      refreshFormData();
    });
    closeModal();
  }
</script>

<style lang="less">
  /deep/.ant-card-body {
    padding: 0 24px;
  }
  @media (min-width: 576px) {
    :where(.css-dev-only-do-not-override-1jz9808).ant-col-sm-18 {
      max-width: 100% !important;
    }
  }
</style>
